package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.api.model.vo.paas.OrderPayChannelFeignVO;
import com.ssy.lingxi.order.api.paas.OrderConfigFeignService;
import com.ssy.lingxi.system.dao.PayWayRepository;
import com.ssy.lingxi.system.dto.request.PayWayRequest;
import com.ssy.lingxi.system.entity.PayWay;
import com.ssy.lingxi.system.service.PayWayService;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* 支付方式配置
* @author wrc
* @date 2020/7/13
*/
@Service
public class PayWayServiceImpl implements PayWayService {
    @Resource
    private PayWayRepository payWayRepository;

    @Resource
    private OrderConfigFeignService orderConfigFeignService;

    /**
     * 查询支付方式配置
     *
     * @author wrc
     * @date 2020/6/11
     */
    @Override
    public Wrapper<List<PayWay>> payWayList() {
        List<PayWay> all = payWayRepository.findAll(Sort.by("id").ascending());
        return Wrapper.success(all);
    }

    /**
     * 修改支付方式
     * @param request 接口参数
     * @author wrc
     * @date 2020/7/13
     */
    @Transactional
    @Override
    public Wrapper<Void> payWayUpdate(PayWayRequest request) {
        List<OrderPayChannelFeignVO> payChannelFeignList = request.getPayWays().stream().map(payWay -> {
            OrderPayChannelFeignVO feignVO = new OrderPayChannelFeignVO();
            feignVO.setPayType(payWay.getPayType());
            feignVO.setPayChannel(payWay.getWayType());
            feignVO.setStatus(payWay.getIsPitchOn());
            return feignVO;
        }).collect(Collectors.toList());
        Wrapper<Void> orderResult = orderConfigFeignService.updateOrderPayChannelStatus(payChannelFeignList);
        if(orderResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(orderResult.getCode(), orderResult.getMessage());
        }

        payWayRepository.saveAll(request.getPayWays());
        return Wrapper.success();
    }
}
